package com.freewater.springboot.demo.testclient;

import com.freewater.springboot.demo.PackageUtils;
import com.freewater.springboot.demo.web.mutipartandjson.User;
import lombok.Data;
import org.springframework.core.io.ClassPathResource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.MultipartBodyBuilder;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

public class BusinessService {

    public Hotel findHotel(RestTemplate restTemplate) {
        return restTemplate.getForObject("/hotels/{id}", Hotel.class, 42);
    }

    public User addUser(RestTemplate restTemplate) throws IOException {
        String userJson = "{\"firstName\":\"free\",\"lastName\":\"water\",\"age\":18,\"address\":\"chengdu\"}";
        String path = PackageUtils.getClassPathFroClass(this.getClass()) + "/data.bin";
        ClassPathResource file = new ClassPathResource(path);
        //
        MultipartBodyBuilder multipartBodyBuilder = new MultipartBodyBuilder();
        multipartBodyBuilder.part("user", userJson.getBytes(StandardCharsets.UTF_8))
                .contentType(MediaType.APPLICATION_JSON)
                .filename("userData.json");
        multipartBodyBuilder.part("file", file.getContentAsByteArray())
                .filename("data.bin");
        //
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.MULTIPART_FORM_DATA);
        HttpEntity<MultiValueMap<String, HttpEntity<?>>> httpEntity = new HttpEntity<>(multipartBodyBuilder.build(), httpHeaders);
        ResponseEntity<User> response = restTemplate.postForEntity("/user/addUser", httpEntity, User.class);
        return response.getBody();
    }

    @Data
    public static class Hotel {
        long id;
        String name;
    }

}
